package com.blue.config;

import com.blue.constant.JwtConstant;
import com.blue.pojo.Result;
import com.blue.util.JacksonUtil;
import com.blue.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class JwtFilter extends GenericFilterBean {

    private RedisTemplate jsonRedisTemplate;

    public JwtFilter(RedisTemplate jsonRedisTemplate) {
        this.jsonRedisTemplate = jsonRedisTemplate;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String jwt = request.getHeader("Token");

        if (jwt == null) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            Claims claims = JwtUtil.getTokenBody(jwt);
            String username = claims.getSubject();
            Object o = jsonRedisTemplate.opsForHash().get(JwtConstant.REDIS_TOKEN_KEY, username);
            if (o == null || !jwt.equals(o.toString())) {
                response.setContentType("application/json;charset=utf-8");
                Result result = Result.create(403, "请先登录！");
                PrintWriter out = response.getWriter();
                out.write(JacksonUtil.writeValueAsString(result));
                out.flush();
                out.close();
                return;
            }

            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.create(403, "凭证已失效，请重新登录！");
            PrintWriter out = response.getWriter();
            out.write(JacksonUtil.writeValueAsString(result));
            out.flush();
            out.close();
            return;
        }

        filterChain.doFilter(request, response);
    }
}
